<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true">
      <el-form-item label="动态标题" prop="trendsTitle">
        <el-input
          v-model="queryParams.trendsTitle"
          placeholder="请输入动态标题"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="动态状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="动态状态"
          clearable
          size="small"
          style="width: 240px"
        >
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="发布时间">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="trendsList" @selection-change="handleSelectionChange">
      <el-table-column type="expand" width="30">
        <template slot-scope="props">
          <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item label="发布人用户名">
              <span>{{ props.row.user.userName }}</span>
            </el-form-item>
            <el-form-item label="发布时间">
              <span>{{ parseTime(props.row.createTime) }}</span>
            </el-form-item>
            <el-form-item label="动态状态">
              <span>{{ statusFormat('status', props.row) }}</span>
            </el-form-item>
            <el-form-item label="被人举报情况">
              <span>{{ statusFormat('report', props.row) }}</span>
            </el-form-item>
            <el-form-item label="评论量">
              <span>{{ props.row.reply }}</span>
            </el-form-item>
            <el-form-item label="阅读量">
              <span>{{ props.row.click }}</span>
            </el-form-item>
            <el-form-item label="点赞量">
              <span>{{ props.row.fabulous }}</span>
            </el-form-item>
            <el-form-item label="收藏量">
              <span>{{ props.row.collection }}</span>
            </el-form-item>
            <el-form-item label="动态内容">
              <span>{{ props.row.remark }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column type="selection" width="45" align="center"/>
      <el-table-column align="center" label="动态编号" prop="trendsId"/>
      <el-table-column align="center" label="动态内容" :show-overflow-tooltip="true" prop="remark" width="200"/>
      <el-table-column align="center" label="发布人" :show-overflow-tooltip="true" prop="user.userName"/>
      <el-table-column label="点赞量" align="center" prop="fabulous"/>
      <el-table-column label="评论量" align="center" prop="reply" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <router-link :to="'/plain/type/reply/'+ scope.row.trendsId" class="link-type">
            <span>{{ scope.row.reply }}</span>
          </router-link>
        </template>
      </el-table-column>
      <el-table-column label="发布时间" align="center" prop="createTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="动态状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="220" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改动态配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="780px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="动态内容" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入动态内容" :maxlength="500" show-word-limit
                        :autosize="{minRows: 5, maxRows: 20}" :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="动态状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in statusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{ dict.dictLabel }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="图片上传">
              <ImageUpload :key="form.trendsId" @imageUpload="imageUpload" :formImg="formImg"></ImageUpload>
            </el-form-item>
          </el-col>
<!--          <el-col :span="24">
            <el-form-item label="内容" prop="trendsContent">
              <editor v-model="form.trendsContent" :min-height="192"/>
            </el-form-item>
          </el-col>-->
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listTrends,
  getTrendsUserId,
  getTrends,
  addTrends,
  updateTrends,
  updateReport,
  updateStatus,
  delReport1, delReport2, delTrends
} from "@/api/system/trends";
import Editor from "@/components/Editor";
import Emotion from "@/components/Emotion";
import {mapGetters} from 'vuex'

export default {
  name: "Trends",
  components: {Editor,Emotion},
  data() {
    return {
      formImg: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 动态表格数据
      trendsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 状态数据字典
      statusOptions: [],
      reportOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        trendsTitle: undefined,
        userId: undefined,
        report: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        remark: [
          {required: true, message: '动态内容不能为空', trigger: 'blur'},
          {min: 1, max: 500, message: '长度在 1 到 500 个字符', trigger: 'blur'}
        ],
        trendsContent: [
          {required: true, message: "动态内容不能为空", trigger: "blur"}
        ],
        trendsTitle: [
          {required: true, message: "动态标题不能为空", trigger: "blur"},
          {min: 3, max: 80, message: '长度在 3 到 80 个字符', trigger: 'blur'}
        ]
      }
    };
  },
  computed: {
    ...mapGetters([
      'user',
    ])
  },
  created() {
    this.getList();
    this.getDicts("sys_normal_disable").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts("sys_report").then(response => {
      this.reportOptions = response.data;
    });
  },
  methods: {
    change(val) {
      if (val) {
        return JSON.parse(val)
      } else {
        return []
      }
    },
    //图片上传返回的数据
    imageUpload(val) {
      this.formImg = val
      this.form.img = JSON.stringify(val);
    },
    /** 查询动态列表 */
    getList() {
      this.loading = true;
      console.log("sss", this.dateRange)
      listTrends(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.trendsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 状态字典翻译
    statusFormat(e, row) {
      if (e == 'status') {
        return this.selectDictLabel(this.statusOptions, row.status);
      } else if (e == 'report') {
        return this.selectDictLabel(this.reportOptions, row.report);
      }
    },
    // 动态状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$confirm('确认要【' + text + '】发布人【' + row.user.userName + '】这条动态吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return updateStatus(row);
      }).then(() => {
        this.msgSuccess(text + "成功");
      }).catch(function () {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        trendsId: undefined,
        userId: undefined,
        trendsTitle: undefined,
        trendsContent: undefined,
        remark: undefined,
        status: "0"
      };
      this.formImg = []
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.trendsId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加动态";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const trendsId = row.trendsId || this.ids
      getTrends(trendsId).then(response => {
        this.form = response.data;
        if (this.form.img) {
          this.formImg = JSON.parse(this.form.img)
          this.formImg.map(item=>{
            item.url=this.changeUrl(item.fileName)
          })
        } else {
          this.formImg = []
        }
        this.open = true;
        this.title = "修改动态";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.trendsId != undefined) {
            updateTrends(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.userId = JSON.parse(JSON.stringify(this.user.userId))
            addTrends(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const trendsIds = row.trendsId || this.ids;
      this.$confirm('是否确认删除动态编号为"' + trendsIds + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delTrends(trendsIds);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      })
    }
  }
}
</script>

<style scoped>
/deep/ .demo-table-expand {
  font-size: 0;
}

/deep/ .demo-table-expand label {
  width: 100px;
  color: #99a9bf;
}

/deep/ .demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 100%;
}
</style>
<style>
/deep/.el-textarea__inner{
  white-space: pre-wrap;
}
</style>
